﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Web.UI;
using System.Configuration;


/// <summary>
/// Class Helper for javascript script building
/// </summary>
public class fgPop
{
    #region members

    private Dictionary<string, string> m_QueryStringItems;
    private List<string> m_ListOfControlToValorize = new List<string>();
    private bool m_JqDocReady = true;
    private string m_FunctionName;
    private string m_PageToLoad = null;
    private int m_PercentWidth = 0;
    private int m_PercentHeight = 0;
    private string m_QueryString = null;
    private bool m_ScrollBar = false;
    private bool m_AddressBar = false;
    private bool m_Resizable = false;
    private bool m_Adorned = false;
    private bool m_Status = false;
    private enEdge m_Edge;
    private int m_Top = 0;
    private int m_Left = 0;
    private bool m_Center = false;
    private bool m_Maximize = false;
    private bool m_Minimize = false;
    private int m_Width = 0;
    private int m_Height = 0;
    private string m_Title = null;
    private bool m_RefreshParent = false;
    private string m_ControlToClick = null;
    private string m_ControlToValorize = null;
    private string m_GetValueFromControlName = null;
    private ControlType m_GetValueFromControlType = ControlType.nullo;
    private bool m_ReturnValueAndText = false;
    private bool m_AlertScriptError = false;
    private bool m_AlertPopupName = false;
    private bool m_AlertReturnValue = false;
    private bool m_AlertCompiledScript = false;
    private bool m_Modal = true;
    private List<string> m_MethodNameList = null;
    private bool m_ForceClose = false;
    private List<CustomDictionary> m_DictionaryKeyList = new List<CustomDictionary>();
    private bool GlobalAlertScriptError = false;
    private bool GlobalAlertPopUpName = false;
    private bool GlobalAlertReturnValue = false;
    private bool GlobalAlertCompiledScript = false;

    #endregion

    #region properties

    /// <summary>
    /// The edge enumerator
    /// </summary>
    public enum enEdge
    {
        /// <summary>
        /// The borde is sunken
        /// </summary>
        sunken = 0,
        /// <summary>
        /// The border is raised
        /// </summary>
        raised = 1
    }

    /// <summary>
    /// The ControlType enumerator
    /// </summary>
    public enum ControlType
    {
        /// <summary>
        /// The control is null
        /// </summary>
        nullo = -1,
        /// <summary>
        /// The control is a TextBox
        /// </summary>
        TextBox = 0,
        /// <summary>
        /// The control is a DropDownList
        /// </summary>
        DropDownList = 1,
        /// <summary>
        /// The control is a ListBox
        /// </summary>
        ListBox = 2,
        /// <summary>
        /// The control is a Label
        /// </summary>
        Label = 3
    }


    /// <summary>
    /// The PopPageType enumerator
    /// </summary>
    public enum PopPageType
    {
        /// <summary>
        /// The popup is BaseConferma
        /// </summary>
        BaseConferma = 1,
        /// <summary>
        /// The popup is BaseNote
        /// </summary>
        BaseNote = 2,
        /// <summary>
        /// The popup is BaseAlert
        /// </summary>
        BaseAlert = 3
    }


    /// <summary>
    /// This script run into jquery (document).ready function if True.
    /// </summary>
    /// <value>
    ///   <c>true</c> if [JQ doc ready]; otherwise, <c>false</c>.
    /// </value>
    /// <remarks>
    /// Both FunctionName and JQDocReady is not permitted.
    /// </remarks>
    public bool JQDocReady
    {
        get { return m_JqDocReady; }
        set { m_JqDocReady = value; }
    }

    /// <summary>
    /// Name of the javascript function
    /// </summary>
    /// <value>
    /// The name of the function.
    /// </value>
    /// <remarks>
    /// Both FunctionName and JQDocReady is not permitted.
    /// </remarks>
    public string FunctionName
    {
        get { return m_FunctionName; }
        set
        {
            if (value.EndsWith("()"))
            {
                m_FunctionName = value;
            }
            else
            {
                m_FunctionName = value + "()";
            }
        }
    }

    /// <summary>
    /// The page to open as popup.
    /// </summary>
    /// <value>
    /// The page to load.
    /// </value>
    public string PageToLoad
    {
        get { return m_PageToLoad; }
        set { m_PageToLoad = value; }
    }

    /// <summary>
    /// The percentage width of the popup relative to the caller window
    /// </summary>
    /// <value>
    /// The width of the percent.
    /// </value>
    public int PercentWidth
    {
        get { return m_PercentWidth; }
        set
        {
            if (value > 100)
            {
                value = 100;
            }
            m_PercentWidth = value;
        }
    }

    /// <summary>
    /// The percentage height of the popup relative to the caller window
    /// </summary>
    /// <value>
    /// The height of the percent.
    /// </value>
    public int PercentHeight
    {
        get { return m_PercentHeight; }
        set
        {
            if (value > 100)
            {
                value = 100;
            }
            m_PercentHeight = value;
        }
    }

    /// <summary>
    /// The query string thet follow the page url, if any.
    /// </summary>
    /// <value>
    /// The query string.
    /// </value>
    public string QueryString
    {
        get { return m_QueryString; }
        set
        {
            try
            {
                if (value.StartsWith("?"))
                {
                    m_QueryString = value;
                }
                else
                {
                    m_QueryString = "?" + value;
                }
                string[] qstring = m_QueryString.Split('&');
                m_QueryStringItems = new Dictionary<string, string>();
                foreach (string s in qstring)
                {
                    m_QueryStringItems.Add(s.Split('=')[0], s.Split('=')[1]);
                }
            }
            catch
            {
                return;
            }

        }
    }

    /// <summary>
    /// Show an alert with the compiled script.
    /// </summary>
    /// <value>
    ///   <c>true</c> if [alert compiled script]; otherwise, <c>false</c>.
    /// </value>
    public bool AlertCompiledScript
    {
        get { return m_AlertCompiledScript; }
        set { m_AlertCompiledScript = value; }
    }

    /// <summary>
    /// Popup use scrollbar if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if [scroll bar]; otherwise, <c>false</c>.
    /// </value>
    public bool ScrollBar
    {
        get { return m_ScrollBar; }
        set { m_ScrollBar = value; }
    }

    /// <summary>
    /// Popup use addressbar if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if [address bar]; otherwise, <c>false</c>.
    /// </value>
    public bool AddressBar
    {
        get { return m_AddressBar; }
        set { m_AddressBar = value; }
    }

    /// <summary>
    /// Popup is resizable if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if resizable; otherwise, <c>false</c>.
    /// </value>
    public bool Resizable
    {
        get { return m_Resizable; }
        set { m_Resizable = value; }
    }

    /// <summary>
    /// Popup use adorned if True.
    /// </summary>
    /// <value>
    ///   <c>true</c> if adorned; otherwise, <c>false</c>.
    /// </value>
    public bool Adorned
    {
        get { return m_Adorned; }
        set { m_Adorned = value; }
    }

    /// <summary>
    /// Popup use statusbar if True.
    /// </summary>
    /// <value>
    ///   <c>true</c> if status; otherwise, <c>false</c>.
    /// </value>
    public bool Status
    {
        get { return m_Status; }
        set { m_Status = value; }
    }

    /// <summary>
    /// The Popup edge (sunken | raised )
    /// </summary>
    /// <value>
    /// The edge.
    /// </value>
    public enEdge Edge
    {
        get { return m_Edge; }
        set { m_Edge = value; }
    }

    /// <summary>
    /// Popup Top
    /// </summary>
    /// <value>
    /// The top.
    /// </value>
    public int Top
    {
        get { return m_Top; }
        set { m_Top = value; }
    }

    /// <summary>
    /// Popup Left
    /// </summary>
    /// <value>
    /// The left.
    /// </value>
    public int Left
    {
        get { return m_Left; }
        set { m_Left = value; }
    }

    /// <summary>
    /// Popup will center on screen
    /// </summary>
    /// <value>
    ///   <c>true</c> if center; otherwise, <c>false</c>.
    /// </value>
    public bool Center
    {
        get { return m_Center; }
        set { m_Center = value; }
    }

    /// <summary>
    /// Popup will show maximize button if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if maximize; otherwise, <c>false</c>.
    /// </value>
    public bool Maximize
    {
        get { return m_Maximize; }
        set { m_Maximize = value; }
    }

    /// <summary>
    /// Popup will show minimize button if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if minimize; otherwise, <c>false</c>.
    /// </value>
    public bool Minimize
    {
        get { return m_Minimize; }
        set { m_Minimize = value; }
    }

    /// <summary>
    /// Popup width
    /// </summary>
    /// <value>
    /// The width.
    /// </value>
    public int Width
    {
        get { return m_Width; }
        set { m_Width = value; }
    }

    /// <summary>
    /// Popup Height
    /// </summary>
    /// <value>
    /// The height.
    /// </value>
    public int Height
    {
        get { return m_Height; }
        set { m_Height = value; }
    }

    /// <summary>
    /// Popup Title
    /// </summary>
    /// <value>
    /// The title.
    /// </value>
    public string Title
    {
        get { return m_Title; }
        set { m_Title = value; }
    }

    /// <summary>
    /// Reload parent page after popup close if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if [refresh parent]; otherwise, <c>false</c>.
    /// </value>
    public bool RefreshParent
    {
        get { return m_RefreshParent; }
        set { m_RefreshParent = value; }
    }


    /// <summary>
    /// The name of server side control that cause refresh of the parent page (this control must support click event)
    /// </summary>
    /// <value>
    /// The control to click.
    /// </value>
    /// <remarks>
    /// (this control must support click event)
    /// </remarks>
    public string ControlToClick
    {
        get { return m_ControlToClick; }
        set { m_ControlToClick = value; }
    }


    /// <summary>
    /// Show the returned value from popup if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if [alert return value]; otherwise, <c>false</c>.
    /// </value>
    public bool AlertReturnValue
    {
        get { return m_AlertReturnValue; }
        set { m_AlertReturnValue = value; }
    }


    /// <summary>
    /// Control to valorize with the popup returned value
    /// </summary>
    /// <value>
    /// The control to valorize.
    /// </value>
    public string ControlToValorize
    {
        get { return m_ControlToValorize; }
        set
        {
            m_ControlToValorize = value;
            m_ListOfControlToValorize.Add(value);
        }
    }


    /// <summary>
    /// Control name to get value from once the popup close
    /// </summary>
    /// <value>
    /// The name of the get value from control.
    /// </value>
    public string GetValueFromControlName
    {
        get { return m_GetValueFromControlName; }
        set { m_GetValueFromControlName = value; }
    }


    /// <summary>
    /// Control type to get value from once the popup close
    /// </summary>
    /// <value>
    /// The type of the get value from control.
    /// </value>
    public ControlType GetValueFromControlType
    {
        get { return m_GetValueFromControlType; }
        set { m_GetValueFromControlType = value; }
    }


    /// <summary>
    /// Return both Value and Text from popup (eg. a listbox wich have two values)
    /// </summary>
    /// <value>
    ///   <c>true</c> if [return value and text]; otherwise, <c>false</c>.
    /// </value>
    public bool ReturnValueAndText
    {
        get { return m_ReturnValueAndText; }
        set { m_ReturnValueAndText = value; }
    }

    /// <summary>
    /// Show the javascript error if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if [show script error]; otherwise, <c>false</c>.
    /// </value>
    public bool AlertScriptError
    {
        get { return m_AlertScriptError; }
        set { m_AlertScriptError = value; }
    }

    /// <summary>
    /// Show the popup name if True
    /// </summary>
    /// <value>
    ///   <c>true</c> if [show popup name]; otherwise, <c>false</c>.
    /// </value>
    public bool AlertPopupName
    {
        get { return m_AlertPopupName; }
        set { m_AlertPopupName = value; }
    }

    /// <summary>
    /// Force to open a popup in modal manner
    /// </summary>
    public bool Modal
    {
        get { return m_Modal; }
        set { m_Modal = value; }
    }


    /// <summary>
    /// Return the name of the method that has call JsPop()
    /// </summary>
    public List<string> MethodNameList
    {
        get { return m_MethodNameList; }
    }


    /// <summary>
    /// Force to close popup
    /// </summary>
    public bool ForceClose
    {
        get { return m_ForceClose; }
        set { m_ForceClose = value; }
    }


    #endregion

    #region costructors

    /// <summary>
    /// Costructor
    /// </summary>
    public fgPop()
    {
        try
        {
            GlobalAlertPopUpName = Convert.ToBoolean(ConfigurationManager.AppSettings["GlobalAlertPopUpName"]);
            GlobalAlertScriptError = Convert.ToBoolean(ConfigurationManager.AppSettings["GlobalAlertScriptError"]);
            GlobalAlertReturnValue = Convert.ToBoolean(ConfigurationManager.AppSettings["GlobalAlertReturnValue"]);
            GlobalAlertCompiledScript = Convert.ToBoolean(ConfigurationManager.AppSettings["GlobalAlertCompiledScript"]);
        }
        catch
        {
            // ("GlobalSettings error: some value in web.config could be incorrect! Author:Gianni");
        }

    }

    #endregion

    #region methods


    /// <summary>
    /// Method JsPop() build the javascript.
    /// </summary>
    /// <returns>
    /// the javascript
    /// </returns>
    public string JsPop(Page page = null)
    {
        try
        {
            AlertPopupName = GlobalAlertPopUpName == false ? false : AlertPopupName;
            AlertScriptError = GlobalAlertScriptError == false ? false : AlertScriptError;
            AlertReturnValue = GlobalAlertReturnValue == false ? false : AlertReturnValue;
            AlertCompiledScript = GlobalAlertCompiledScript == false ? false : AlertCompiledScript;

            string pop = null;
            StringBuilder js = new StringBuilder();
            js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");

            if ((Width > 0 && Height <= 0) || (Height > 0 && Width <= 0))
            {
                throw new Exception("One of the properties: Width or Height are not set properly ! Author:Gianni");
            }

            if (((Width <= 0 && Height <= 0) || (Height <= 0 && Width <= 0)) && (PercentWidth <= 0 || PercentHeight <= 0))
            {
                throw new Exception("A popup must have a size, please specify Width - Height or PercentWidth - PercentHeight! Author:Gianni");
            }

            if ((PercentWidth > 0 || PercentHeight > 0) && (Width > 0 || Height > 0))
            {
                throw new Exception("Properties: PercentWidth or PercentHeight are in comflict with Width or Height ! Author:Gianni");
            }

            if ((Top > 0 || Left > 0) && (Center == true))
            {
                throw new Exception("Properties: Top or Left are in comflict with Center property! Author:Gianni");
            }

            if (AlertReturnValue && !Modal)
            {
                throw new Exception("Properties: AlertReturnValue comflict with Modal! Author:Gianni");
            }

            if (ControlToValorize != null && !Modal)
            {
                throw new Exception("Properties: ControlToValorize comflict with Modal! Author:Gianni");
            }

            if (RefreshParent == true && !Modal)
            {
                throw new Exception("Properties: RefreshParent comflict with Modal! Author:Gianni");
            }

            if (JQDocReady == true && FunctionName != null)
            {
                throw new Exception("Properties: JQDocReady comflict with FunctionName! Author:Gianni");
            }


            // START APPENDING SCRIPT ////////////////////////////////////////////////////////////////////////////////////////////////

            if (JQDocReady)
            {
                js.AppendLine("$(document).ready(function () {");
            }
            else
            {
                js.AppendLine("function " + FunctionName + "{");
            }

            if (AlertPopupName)
            {
                js.AppendLine("     alert('Popup: " + PageToLoad + " will open.');");
            }

            js.AppendLine("     try");
            js.AppendLine("     {");
            js.AppendLine("     var winW = $(window).width();");
            js.AppendLine("     var winH = $(window).height();");
            js.AppendLine("     var percentH = (winH * " + PercentHeight.ToString() + ") / 100;");
            js.AppendLine("     var percentW = (winW * " + PercentWidth.ToString() + ") / 100;");
            js.AppendLine("     var url = '" + PageToLoad + QueryString + "';");

            //POPUP COMPOSITION 
            if (ScrollBar)
            {
                pop += "scroll:yes;";
            }
            else
            {
                pop += "scroll:no;";
            }

            if (AddressBar)
            {
                pop += "addressbar:yes;";
            }
            else
            {
                pop += "addressbar:no;";
            }

            if (Resizable)
            {
                pop += "resizable:1;";
            }
            else
            {
                pop += "resizable:0;";
            }

            if (Adorned)
            {
                pop += "unadorned:yes;";
            }
            else
            {
                pop += "unadorned:no;";
            }

            if (Status)
            {
                pop += "status=yes;";
            }
            else
            {
                pop += "status=no;";
            }

            if (Edge == enEdge.raised)
            {
                pop += "edge:raised;";
            }
            else
            {
                pop += "edge:sunken;";
            }

            if (Center)
            {
                pop += "center=yes;";
            }
            else
            {
                pop += "center=no;";
            }

            if (Maximize)
            {
                pop += "maximize:yes;";
            }
            else
            {
                pop += "maximize:no;";
            }

            if (Minimize)
            {
                pop += "minimize:yes;";
            }
            else
            {
                pop += "minimize:no;";
            }

            if (Top > 0)
            {
                pop += "dialogTop:" + Top.ToString() + "px;";
            }

            if (Left > 0)
            {
                pop += "dialogLeft:" + Left.ToString() + "px;";
            }

            if (Height > 0 | Width > 0)
            {
                pop += "dialogHeight:" + Height.ToString() + "px;dialogwidth:" + Width.ToString() + "px";
            }
            else
            {
                pop += "dialogHeight:' + percentH + 'px;dialogwidth:' + percentW + 'px";
            }

            js.AppendLine("     var pop = '" + pop + "';");

            if (AlertCompiledScript)
            {
                js.AppendLine("     alert(pop);");
            }

            if (Modal)
            {
                js.AppendLine("     var oReturnValue = window.showModalDialog(url, '', pop);");
            }
            else
            {
                js.AppendLine("      window.open(url, '', pop);");
            }

            if (AlertReturnValue)
            {
                js.AppendLine("     alert('Value from popup:' + oReturnValue.selectedValue + ' - Text from popup: ' + oReturnValue.selectedText);");
            }

            if (ControlToValorize != null)
            {
                if (m_ListOfControlToValorize.Count == 1)
                {
                    js.AppendLine("         $('#" + m_ListOfControlToValorize[0] + "').val(oReturnValue.selectedValue).change();");
                }
                if (m_ListOfControlToValorize.Count == 2)
                {
                    js.AppendLine("         $('#" + m_ListOfControlToValorize[0] + "').val(oReturnValue.selectedValue).change();");
                    js.AppendLine("         $('#" + m_ListOfControlToValorize[1] + "').val(oReturnValue.selectedText);");
                }
            }


            if (RefreshParent == true && ControlToClick != null)
            {
                js.AppendLine("     document.all('" + ControlToClick + "').click();");
            }

            //if ((RefreshParent == true && ControlToClick == null) || (RefreshParent == false && ControlToClick != null))
            //{
            //    throw new Exception("One of the two properties: RefreshParent or ControlToClick is missing! Author:Gianni");
            //}

            js.AppendLine("     }");
            js.AppendLine("     catch (err)");
            js.AppendLine("     {");
            if (AlertScriptError)
            {
                js.AppendLine("         alert('Script error: ' + err + ' Author:Gianni');");
            }
            js.AppendLine("     }");

            if (JQDocReady)
            {
                js.AppendLine(" });");
            }
            else
            {
                js.AppendLine(" }");
            }

            js.AppendLine("</script>");

            ResetAllProperties();

            m_MethodNameList = new List<string>();
            StackTrace st = new StackTrace(true);
            foreach (StackFrame f in st.GetFrames())
            {
                m_MethodNameList.Add(f.GetMethod().Name);
            }

            string script = js.ToString();

            if (page != null)
            {
                ScriptManager.RegisterStartupScript(page, page.GetType(), Guid.NewGuid().ToString(), script, false);
            }

            return script;
        }
        catch (Exception ex)
        {
            StringBuilder js = new StringBuilder();
            js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");
            js.AppendLine("     alert('" + ex.Message + "');");
            js.AppendLine("</script>");
            ResetAllProperties();
            return js.ToString();
        }

    }

    /// <summary>
    /// Method JsClosePop() build the script to close a popup.
    /// </summary>
    /// <returns>
    /// the javascript
    /// </returns>
    public string JsClosePop(Page page = null)
    {
        try
        {
            AlertPopupName = GlobalAlertPopUpName == false ? false : AlertPopupName;
            AlertScriptError = GlobalAlertScriptError == false ? false : AlertScriptError;
            AlertReturnValue = GlobalAlertReturnValue == false ? false : AlertReturnValue;
            AlertCompiledScript = GlobalAlertCompiledScript == false ? false : AlertCompiledScript;

            StringBuilder js = new StringBuilder();
            js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");

            if (JQDocReady == false && FunctionName == null)
            {
                throw new Exception("Please specify how script react: JQDocReady or FunctionName! Author:Gianni");
            }

            if (JQDocReady)
            {
                js.AppendLine("     var o = new Object();");
                js.AppendLine("$(document).ready(function () {");
            }
            else
            {
                js.AppendLine("     var o = new Object();");
                js.AppendLine("function " + FunctionName + "{");
            }

            if ((GetValueFromControlName == null && GetValueFromControlType != ControlType.nullo) || (GetValueFromControlName != null && GetValueFromControlType == ControlType.nullo))
            {
                throw new Exception("One of the two properties: GetValueFromControlName or GetValueFromControlType is missing! Author:Gianni");
            }

            if (GetValueFromControlType == ControlType.ListBox || GetValueFromControlType == ControlType.DropDownList)
            {
                js.AppendLine("     $(function () {");
                js.AppendLine("     var o = new Object();");
                js.AppendLine("     var obj = $('select[id*=" + (char)34 + GetValueFromControlName + (char)34 + "]').change(function () {");
                js.AppendLine("     o.selectedValue = $('select[id*=" + (char)34 + GetValueFromControlName + (char)34 + "]').val();");
                js.AppendLine("     o.selectedText = $('select[id*=" + (char)34 + GetValueFromControlName + (char)34 + "] option:selected').text();");

                if (m_DictionaryKeyList.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CustomDictionary cd in m_DictionaryKeyList)
                    {
                        if (cd.TypeOfControl == CustomDictionary.ControlType.ListBox || cd.TypeOfControl == CustomDictionary.ControlType.DropDownList)
                        {
                            sb.Append((char)34 + cd.Key + "=" + (char)34 + " + $('select[id*=" + (char)34 + cd.ControlName + (char)34 + "] option:selected').val()").Append(" + 'Ç' + ");
                        }
                        if (cd.TypeOfControl == CustomDictionary.ControlType.TextBox)
                        {
                            sb.Append("'" + cd.Key + "=' + $('#" + cd.ControlName + "').val()").Append(" + 'Ç' + ");
                        }
                        if (cd.TypeOfControl == CustomDictionary.ControlType.Label)
                        {
                            sb.Append("'" + cd.Key + "=' + $('#" + cd.ControlName + "').text()").Append(" + 'Ç' + ");
                        }
                    }
                    js.AppendLine("     o.dictionaryValues = " + sb.ToString().Remove(sb.ToString().Length - 9) + ";");
                    sb = null;
                }

                if (AlertReturnValue)
                {
                    js.AppendLine("     alert('Selected value: ' + o.selectedValue + ' - Selected text: ' + o.selectedText);");
                }
                js.AppendLine("     window.returnValue = o;");
                js.AppendLine("     window.close();");
                js.AppendLine("     });");
                js.AppendLine("     });");
            }

            if (GetValueFromControlType == ControlType.TextBox || GetValueFromControlType == ControlType.Label)
            {
                js.AppendLine("     o.selectedValue = $('#" + GetValueFromControlName + "').val();");
                js.AppendLine("     o.selectedText = $('#" + GetValueFromControlName + "').val();");

                if (m_DictionaryKeyList.Count > 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (CustomDictionary cd in m_DictionaryKeyList)
                    {
                        if (cd.TypeOfControl == CustomDictionary.ControlType.ListBox || cd.TypeOfControl == CustomDictionary.ControlType.DropDownList)
                        {
                            sb.Append((char)34 + cd.Key + "=" + (char)34 + " + $('select[id*=" + (char)34 + cd.ControlName + (char)34 + "] option:selected').val()").Append(" + 'Ç' + ");
                        }
                        if (cd.TypeOfControl == CustomDictionary.ControlType.TextBox)
                        {
                            sb.Append("'" + cd.Key + "=' + $('#" + cd.ControlName + "').val()").Append(" + 'Ç' + ");
                        }
                        if (cd.TypeOfControl == CustomDictionary.ControlType.Label)
                        {
                            sb.Append("'" + cd.Key + "=' + $('#" + cd.ControlName + "').text()").Append(" + 'Ç' + ");
                        }
                    }
                    js.AppendLine("     o.dictionaryValues = " + sb.ToString().Remove(sb.ToString().Length - 9) + ";");
                    sb = null;
                }

                js.AppendLine("     window.returnValue = o;");
                js.AppendLine("     window.close();");
            }

            if (GetValueFromControlType == ControlType.nullo && GetValueFromControlName == null)
            {
                js.AppendLine("     window.close();");
            }

            if (AlertCompiledScript)
            {
                js.AppendLine("     alert(pop);");
            }

            if (JQDocReady)
            {
                js.AppendLine(" });");
            }
            else
            {
                js.AppendLine(" }");
            }


            if (GetValueFromControlType == ControlType.ListBox || GetValueFromControlType == ControlType.DropDownList)
            {
                //js.AppendLine("     function close()");
                //js.AppendLine("     {");
                //js.AppendLine("         window.close();");
                //js.AppendLine("     }");
            }

            if (GetValueFromControlType == ControlType.TextBox)
            {
                //js.AppendLine("     function close()");
                //js.AppendLine("     {");
                //js.AppendLine("         window.close();");
                //js.AppendLine("     }");
            }


            js.AppendLine("</script>");

            ResetAllProperties();

            m_MethodNameList = new List<string>();
            StackTrace st = new StackTrace(true);
            foreach (StackFrame f in st.GetFrames())
            {
                m_MethodNameList.Add(f.GetMethod().Name);
            }

            string script = js.ToString();

            if (page != null)
            {
                ScriptManager.RegisterStartupScript(page, page.GetType(), Guid.NewGuid().ToString(), script, false);
            }

            return script;

        }
        catch (Exception ex)
        {
            StringBuilder js = new StringBuilder();
            js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");
            js.AppendLine("     alert('" + ex.Message + "');");
            js.AppendLine("</script>");
            ResetAllProperties();
            return js.ToString();
        }

    }


    /// <summary>
    /// Method JsAlert() build the script to ope popup as alert.
    /// </summary>
    /// <param name="message"></param>
    /// <param name="pageType"></param>
    /// <returns>the javascript</returns>
    public string JsAlert(string message, PopPageType pageType)
    {
        try
        {

            string popPath = "popups/";

            if (pageType == PopPageType.BaseAlert)
            {
                PageToLoad = popPath + PopPageType.BaseAlert + ".aspx";
            }

            if (pageType == PopPageType.BaseConferma)
            {
                PageToLoad = popPath + PopPageType.BaseConferma + ".aspx";
            }

            if (pageType == PopPageType.BaseNote)
            {
                PageToLoad = popPath + PopPageType.BaseNote + ".aspx";
            }

            JQDocReady = true;
            QueryString = "?message=" + message;
            PercentWidth = 50;
            PercentHeight = 40;
            Edge = enEdge.raised;
            Title = "Titolo 01";

            string pop = null;
            StringBuilder js = new StringBuilder();
            js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");

            if (JQDocReady)
            {
                js.AppendLine("$(document).ready(function () {");
            }
            else
            {
                js.AppendLine("function " + FunctionName + "() {");
            }

            js.AppendLine("     var winW = $(window).width();");
            js.AppendLine("     var winH = $(window).height();");
            js.AppendLine("     var percentH = (winH * " + PercentHeight.ToString() + ") / 100;");
            js.AppendLine("     var percentW = (winW * " + PercentWidth.ToString() + ") / 100;");
            js.AppendLine("     var url = '" + PageToLoad + QueryString + "';");

            if (ScrollBar)
            {
                pop += "scroll:yes;";
            }
            else
            {
                pop += "scroll:no;";
            }

            if (AddressBar)
            {
                pop += "addressbar:yes;";
            }
            else
            {
                pop += "addressbar:no;";
            }

            if (Resizable)
            {
                pop += "resizable:1;";
            }
            else
            {
                pop += "resizable:0;";
            }

            if (Adorned)
            {
                pop += "unadorned:yes;";
            }
            else
            {
                pop += "unadorned:no;";
            }

            if (Status)
            {
                pop += "status=yes;";
            }
            else
            {
                pop += "status=no;";
            }

            if (Edge == enEdge.raised)
            {
                pop += "edge:raised;";
            }
            else
            {
                pop += "edge:sunken;";
            }

            if (Center)
            {
                pop += "center=yes;";
            }
            else
            {
                pop += "center=no;";
            }

            if (Maximize)
            {
                pop += "maximize:yes;";
            }
            else
            {
                pop += "maximize:no;";
            }

            if (Minimize)
            {
                pop += "minimize:yes;";
            }
            else
            {
                pop += "minimize:no;";
            }

            if (Top > 0)
            {
                pop += "dialogTop:" + Top.ToString() + "px;";
            }

            if (Left > 0)
            {
                pop += "dialogLeft:" + Left.ToString() + "px;";
            }

            if (Height > 0 | Width > 0)
            {
                pop += "dialogHeight:" + Height.ToString() + "px;dialogwidth:" + Width.ToString() + "px";
            }
            else
            {
                pop += "dialogHeight:' + percentH + 'px;dialogwidth:' + percentW + 'px";
            }

            js.AppendLine("     var pop = '" + pop + "';");

            if (AlertCompiledScript)
            {
                js.AppendLine("     alert(pop);");
            }

            js.AppendLine("     var oReturnValue = window.showModalDialog(url, '', pop);");

            if (ControlToValorize != null)
            {
                if (m_ListOfControlToValorize.Count == 1)
                {
                    if (pageType == PopPageType.BaseNote)
                    {
                        js.AppendLine("         $('#" + m_ListOfControlToValorize[0] + "').val(oReturnValue.selectedValue + 'Ç' + oReturnValue.selectedText);");
                    }
                    else
                    {
                        js.AppendLine("         $('#" + m_ListOfControlToValorize[0] + "').val(oReturnValue.selectedValue);");
                    }
                }
                if (m_ListOfControlToValorize.Count == 2)
                {
                    js.AppendLine("         $('#" + m_ListOfControlToValorize[0] + "').val(oReturnValue.selectedValue);");
                    js.AppendLine("         $('#" + m_ListOfControlToValorize[1] + "').val(oReturnValue.selectedText);");
                }

            }

            if (RefreshParent == true && ControlToClick != null)
            {
                js.AppendLine("     document.all('" + ControlToClick + "').click();");
            }

            if ((RefreshParent == true && ControlToClick == null) || (RefreshParent == false && ControlToClick != null))
            {
                throw new Exception("One of the two properties: RefreshParent or ControlToClick is missing! Author:Gianni");
            }

            if (JQDocReady)
            {
                js.AppendLine(" });");
            }
            else
            {
                js.AppendLine(" }");
            }

            js.AppendLine("</script>");

            ResetAllProperties();

            return js.ToString();


        }
        catch (Exception ex)
        {
            StringBuilder js = new StringBuilder();
            js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");
            js.AppendLine("     alert('" + ex.Message + "');");
            js.AppendLine("</script>");
            ResetAllProperties();
            return js.ToString();

        }

    }

    /// <summary>
    /// Method JsKey() will generate a new guid as javascript key.
    /// </summary>
    /// <returns>GUID</returns>
    public string jsKey()
    {
        return Guid.NewGuid().ToString();
    }

    private void ResetAllProperties()
    {
        m_ListOfControlToValorize = null;
        m_JqDocReady = true;
        m_FunctionName = null;
        m_PageToLoad = null;
        m_PercentWidth = 0;
        m_PercentHeight = 0;
        m_QueryString = string.Empty;
        m_AlertCompiledScript = false;
        m_ScrollBar = false;
        m_AddressBar = false;
        m_Resizable = false;
        m_Adorned = false;
        m_Status = false;
        m_Top = 0;
        m_Left = 0;
        m_Center = true;
        m_Maximize = false;
        m_Minimize = false;
        m_Width = 0;
        m_Height = 0;
        m_Title = null;
        m_RefreshParent = false;
        m_ControlToClick = null;
        m_AlertReturnValue = false;
        m_ControlToValorize = null;
        m_GetValueFromControlName = null;
        m_GetValueFromControlType = ControlType.nullo;
        m_ReturnValueAndText = false;
        m_AlertScriptError = false;
        m_AlertPopupName = false;
        m_Modal = true;
        m_DictionaryKeyList.Clear();
        m_DictionaryKeyList = null;
    }


    /// <summary>
    /// Add a key value to the dictionary
    /// </summary>
    /// <param name="key"></param>
    /// <param name="controlName"></param>
    /// <param name="controlType"></param>
    public void AddKeyToDictionary(string key, string controlName, CustomDictionary.ControlType controlType)
    {
        m_DictionaryKeyList.Add(new CustomDictionary { Key = key, ControlName = controlName, TypeOfControl = controlType });
    }

    /// <summary>
    /// Save data to clipboard
    /// </summary>
    /// <param name="page"></param>
    /// <param name="content"></param>
    public void SetClipBoard(Page page, string content)
    {
        //Only on IE
        StringBuilder js = new StringBuilder();
        js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");
        js.AppendLine("     $(document).ready(function () {");
        js.AppendLine("         clipboardData.setData('text','" + content + "');");
        js.AppendLine("     });");
        js.AppendLine("</script>");
        string s = js.ToString();
        ScriptManager.RegisterStartupScript(page, page.GetType(), "key", s, false);
    }

    /// <summary>
    /// Get data from clipboard
    /// </summary>
    /// <param name="page"></param>
    /// <param name="controlToValorize"></param>
    public void GetClipBoard(Page page, string controlToValorize)
    {
        StringBuilder js = new StringBuilder();
        js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");
        js.AppendLine("     $(document).ready(function () {");
        js.AppendLine("         var clip = clipboardData.getData('text');");
        js.AppendLine("         $('#" + controlToValorize + "').val(clip);");
        js.AppendLine("     });");
        js.AppendLine("</script>");
        string s = js.ToString();
        ScriptManager.RegisterStartupScript(page, page.GetType(), "key", s, false);
    }

    /// <summary>
    /// Clear the clipboard
    /// </summary>
    /// <param name="page"></param>
    public void ClearClipBoard(Page page)
    {
        StringBuilder js = new StringBuilder();
        js.AppendLine("<script language=\"javascript\" type=\"text/javascript\">");
        js.AppendLine("     $(document).ready(function () {");
        js.AppendLine("          clipboardData.clearData('text');");
        js.AppendLine("     });");
        js.AppendLine("</script>");
        string s = js.ToString();
        ScriptManager.RegisterStartupScript(page, page.GetType(), "key", s, false);
    }


    #endregion

}

